package com.lemi.controller;

import com.alibaba.fastjson.JSONObject;
import com.lemi.dao.MenuMapper;
import com.lemi.dao.MenuOperationMapper;
import com.lemi.entity.Menu;
import com.lemi.entity.MenuOperation;
import com.lemi.entity.User;
import com.lemi.util.BspEntity;
import com.lemi.util.BspResult;
import com.lemi.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {

    @Value("${server.servlet.context-path}")
    private String appName;

    @Resource
    private MenuMapper menuMapper;

    @Resource
    public MenuOperationMapper menuOperationMapper;

    /**
     * 跳转登陆页
     * @return
     */
    @RequestMapping("/")
    public String index(HttpSession session,Model model){
        User user = (User)session.getAttribute(Constant.SESSION_USER_INFO);
        Object menus = getMenus(user);
        model.addAttribute(Constant.MENU_TREE, JSONObject.toJSONString(menus));
        return "home2";
    }

    /**
     * 通过登录用户，菜单id获取该用户操作按钮权限
     * @param session
     * @param bspEntity
     * @return
     */
    @RequestMapping("getOperations")
    @ResponseBody
    public Object getOperations(HttpSession session, BspEntity bspEntity){
        try {
            User user = (User)session.getAttribute(Constant.SESSION_USER_INFO);
            bspEntity.setId(user.getId());
            List<MenuOperation> operations = menuOperationMapper.getOperationIdsByUser(bspEntity);
            return BspResult.ok("",operations);
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }


    public Object getMenus(User user) {
        try {
            if(StringUtils.isNotBlank(user.getUserName())){

                List<String> userMenuIds = menuMapper.getMenuIdsByUser(user.getUserName());

                Example example = new Example(Menu.class);
                example.setOrderByClause(" parent_id,menu_order ");
                example.createCriteria().andEqualTo("delFlag",false);
                List<Menu> allMenus = menuMapper.selectByExample(example);

                List<Menu> rootMenus = new ArrayList<Menu>();
                for (Menu sysMenu : allMenus) {
                    if(StringUtils.isBlank(sysMenu.getParentId()))
                        rootMenus.add(sysMenu);
                }

                List<Menu> resultMenus = new ArrayList<Menu>();
                for (Menu sysMenu : rootMenus) {
                    if(userMenuIds.contains(sysMenu.getId()+"")) {
                        resultMenus.add(sysMenu);
                    }else {
                        formMenuNode(userMenuIds, allMenus,sysMenu);
                        if(sysMenu.getChildMenus()!=null)
                            resultMenus.add(sysMenu);
                    }
                }
                return resultMenus;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }

    public static void formMenuNode(List<String> userMenuIds, List<Menu> allMenus, Menu thisMenu) {
        List<Menu> formMenus = new ArrayList<Menu>();
        for (Menu sysMenu : allMenus) {
            if(thisMenu.getId().toString().equals(sysMenu.getParentId())) {
                if(StringUtils.isNotBlank(sysMenu.getMenuUrl())) {
                    if(userMenuIds.contains(sysMenu.getId()+""))
                        formMenus.add(sysMenu);
                }else {
                    formMenuNode(userMenuIds, allMenus, sysMenu);
                    if(sysMenu.getChildMenus()!=null && !sysMenu.getChildMenus().isEmpty())
                        formMenus.add(sysMenu);
                }
            }
        }
        if(!formMenus.isEmpty())
            thisMenu.setChildMenus(formMenus);
    }

}
